package com.learn.sixday;

import com.google.common.collect.Lists;

import java.util.LinkedList;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/14
 */
public class ProducerConsumer {

}

class MessageQueue {
    //    消息的队列集合
    private LinkedList<Message> list = Lists.newLinkedList();
    //    队列容量
    private int capcity;

    //    获取消息
    public Message take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message message = list.removeFirst();
            list.notifyAll();
            return message;
        }
    }

    //    生产消息
    public void put(Message message) {
        synchronized (list) {
            while (list.size() >= capcity) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            list.notifyAll();
        }
    }
}

final class Message { //final不可继承，子类也就无法重写里面的方法
    private int id;

    private Object value;

    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    public int getId() {
        return id;
    }

    public Object getMessage() {
        return value;
    }
}
